package com.dunshan.dunshanmongodb.service.Impl;

import com.dunshan.dunshanmongodb.pojo.MongoTest;
import com.dunshan.dunshanmongodb.pojo.User;
import com.dunshan.dunshanmongodb.service.MongoTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MongoTestServiceImpl implements MongoTestService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(MongoTest user) {
        mongoTemplate.insert(user);
    }

    @Override
    public void saveAll(List<MongoTest> userList) {
        mongoTemplate.insertAll(userList);
    }

    @Override
    public void delete(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, MongoTest.class);
    }

    @Override
    public MongoTest findById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, MongoTest.class);
    }

    @Override
    public MongoTest findByName(String name) {
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, MongoTest.class);
    }

    @Override
    public List<MongoTest> testFindAll() {
        return mongoTemplate.findAll(MongoTest.class);
    }

    @Override
    public void updateTest(MongoTest test) {
        Query query = new Query(Criteria.where("id").is(test.getId()));
        Update update = new Update().set("age", test.getAge()).set("name", test.getNameName());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query, update, MongoTest.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,TestEntity.class);

    }

    @Override
    public List<User> findAll() {
        List<User> users = mongoTemplate.findAll(User.class);
        return users;
    }


}
